package kr.or.kosta.otr.controller.admincontroller;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import kr.or.kosta.otr.service.adminservice.AdminService;
import kr.or.kosta.otr.utill.NoticeListVO;
import kr.or.kosta.otr.vo.AdminVO;
import kr.or.kosta.otr.vo.CompanyVO;
import kr.or.kosta.otr.vo.IndustryVO;
import kr.or.kosta.otr.vo.MentorVO;
import kr.or.kosta.otr.vo.MessageTypeVO;
import kr.or.kosta.otr.vo.MessageVO;
import kr.or.kosta.otr.vo.NoticeVO;
import kr.or.kosta.otr.vo.ProfessionVO;
import kr.or.kosta.otr.vo.RegionVO;
import kr.or.kosta.otr.vo.UserVO;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class AdminController {
	String savePath;
	@Resource(name = "AdminService")
	AdminService adminService;

	@Resource(name = "C_fileUploadProperties")
	Properties C_fileUploadProperties;

	@RequestMapping(value = "/registerCompany.action")
	public ModelAndView addCompany(@ModelAttribute CompanyVO vo,
			@RequestParam(value = "industryName") String industryName,
			@RequestParam(value = "regionName") String regionName,
			@RequestParam(value = "uploadFile") MultipartFile uploadFile)
					throws Exception {

		HashMap<String, Object> map = new HashMap<String, Object>();

		map.put("industry", "industry_name");
		map.put("industryValue", industryName);

		map.put("region", "region_name");
		map.put("regionValue", regionName);

		vo.setIndustryVo(adminService.getIndustry(map));
		vo.setRegionVo(adminService.getRegion(map));

		// 파일 업로드
		if (uploadFile != null && !uploadFile.isEmpty()) {
			MultipartFile file = uploadFile;
			savePath = C_fileUploadProperties.getProperty("file.upload.path");

			File saveDir = new File(savePath);// 디렉토리 파일을 생성
			if (!saveDir.exists()) {// 디렉토리 파일이 존재하지 않는다면 생성
				saveDir.mkdir();
			}// end if

			String fileName = uploadFile.getOriginalFilename();// 원래의 파일이름을
			// 가져옴.(파일이름이
			// 변경되서 들어가기
			// 때문에)
			vo.setCompanyCi(fileName); // 파일 이름 companyCi에 바인딩

			File saveFile = new File(savePath + "/" + fileName);
			uploadFile.transferTo(saveFile);// 서버에 있는 파일을 설정한 경로로 가져옴.

		}

		adminService.addCompany(vo);

		return new ModelAndView("admin/admin_company_register");
	}

	@RequestMapping(value = "/checkCompany.action")
	public ModelAndView checkCompany(
			@RequestParam(value = "companyName") String companyName,
			@RequestParam(value = "regionName") String regionName)
					throws SQLException {

		HashMap<String, String> map1 = new HashMap<String, String>();
		map1.put("companyName", companyName);
		map1.put("regionName", regionName);
		CompanyVO cvo = adminService.checkCompany(map1);

		String message = "해당 기업이 이미 등록되어 있습니다.";
		if (cvo == null) {
			message = null;
		}

		return new ModelAndView("JsonView", "message", message);
	}

	@RequestMapping(value = "/getAllList2.action")
	public ModelAndView getAllList(@ModelAttribute UserVO vo)
			throws SQLException {
		HashMap<String, ArrayList> map = new HashMap<String, ArrayList>();

		ArrayList<CompanyVO> companyList = adminService.getAllCompany();
		ArrayList<IndustryVO> industryList = adminService.getAllIndustry();
		ArrayList<RegionVO> regionList = adminService.getAllRegion();
		ArrayList<ProfessionVO> professionList = adminService
				.getAllProfession();

		map.put("companyList", companyList);
		map.put("industryList", industryList);
		map.put("regionList", regionList);
		map.put("professionList", professionList);

		return new ModelAndView("admin/admin_company_register", "listMap", map);
	}

	@RequestMapping(value = "/getComapnyByCompanyName.action")
	public ModelAndView getComapnyByCompanyName(
			@RequestParam(value = "companyName") String companyName)
					throws SQLException {
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("company", "company_name");
		map.put("companyValue", companyName);
		ArrayList<CompanyVO> list = adminService.getCompanyInfo(map);
		return new ModelAndView("admin/admin_company_search", "list", list);
	}

	@RequestMapping(value = "/deleteCompany.action")
	public ModelAndView deleteCompany(
			@RequestParam(value = "companyId") int companyId,
			@RequestParam(value = "companyName") String companyName)
					throws SQLException {
		adminService.deleteCompany(companyId);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("company", "company_name");
		map.put("companyValue", companyName);
		ArrayList<CompanyVO> list = adminService.getCompanyInfo(map);
		return new ModelAndView("admin/admin_company_search", "list", list);
	}

	@RequestMapping(value = "/getAllMentor.action")
	public ModelAndView getAllMentor(
			@RequestParam(value = "companyId") int companyId,
			@RequestParam(value = "companyName") String companyName)
					throws SQLException {
		adminService.deleteCompany(companyId);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("company", "company_name");
		map.put("companyValue", companyName);
		ArrayList<CompanyVO> list = adminService.getCompanyInfo(map);
		return new ModelAndView("admin/admin_company_search", "list", list);
	}

	@RequestMapping(value = "/getOneCompany.action")
	public ModelAndView getOneCompany(
			@RequestParam(value = "companyId") int companyId)
					throws SQLException {
		CompanyVO vo = adminService.getOneCompany(companyId);
		return new ModelAndView("admin/admin_company_update", "cvo", vo);
	}

	@RequestMapping(value = "/updateCompany.action")
	public ModelAndView updateCompany(@ModelAttribute CompanyVO vo,
			@RequestParam(value = "industryName") String industryName,
			@RequestParam(value = "regionName") String regionName,
			MultipartHttpServletRequest multipartRequest)
					throws Exception {

		HashMap<String, Object> map = new HashMap<String, Object>();
		
		//파일이 있다면 다시 업로드
		MultipartFile uploadFile = multipartRequest.getFile("uploadFile");
		
		if (uploadFile != null && !uploadFile.isEmpty()) {
			MultipartFile file = uploadFile;
			savePath = C_fileUploadProperties.getProperty("file.upload.path");

			File saveDir = new File(savePath);// 디렉토리 파일을 생성
			if (!saveDir.exists()) {// 디렉토리 파일이 존재하지 않는다면 생성
				saveDir.mkdir();
			}// end if

			String fileName = uploadFile.getOriginalFilename();// 원래의 파일이름을
			// 가져옴.(파일이름이
			// 변경되서 들어가기
			// 때문에)
			vo.setCompanyCi(fileName); // 파일 이름 companyCi에 바인딩

			File saveFile = new File(savePath + "/" + fileName);
			uploadFile.transferTo(saveFile);// 서버에 있는 파일을 설정한 경로로 가져옴.

		}
		map.put("industry", "industry_name");
		map.put("industryValue", industryName);

		map.put("region", "region_name");
		map.put("regionValue", regionName);

		vo.setIndustryVo(adminService.getIndustry(map));
		vo.setRegionVo(adminService.getRegion(map));

		adminService.updateCompany(vo);
		return new ModelAndView("admin/admin_company_search");
	}

	@RequestMapping(value = "/wirteNotice.action")
	public ModelAndView writeNotice(@ModelAttribute AdminVO avo,
			@RequestParam(value = "notice_title") String notice_title,
			@RequestParam(value = "notice_content") String notice_content)
					throws SQLException {
		NoticeVO nvo = new NoticeVO();

		// 나중에 삭제
		avo.setAdminId("lmw");

		nvo.setAdminVo(avo);
		nvo.setNoticeTitle(notice_title);
		nvo.setNoticeContent(notice_content);

		NoticeVO rvo = adminService.writeNotice(nvo);

		return new ModelAndView("admin/notice_write_result", "rvo", rvo);
	}

	@RequestMapping(value = "/updateView.action")
	public ModelAndView updateNotice(
			@RequestParam(value = "noticeId") String noticeId)
					throws SQLException {
		int nid = Integer.parseInt(noticeId);
		NoticeVO nvo = adminService.getOneNotice(nid);
		return new ModelAndView("admin/notice_update", "nvo", nvo);
	}

	@RequestMapping(value = "/updateNotice.action")
	public ModelAndView updateNoticeView(
			@RequestParam(value = "noticeId") String noticeId,
			@RequestParam(value = "updateTitle") String updateTitle,
			@RequestParam(value = "updateContent") String updateContent)
					throws SQLException {
		int nid = Integer.parseInt(noticeId);
		NoticeVO nvo = new NoticeVO(nid, null, updateTitle, updateContent, null);
		adminService.updateNotice(nvo);
		return new ModelAndView("admin/notice_update_result", "rvo",
				adminService.getOneNotice(nid));
	}

	@RequestMapping(value = "/deleteNotice.action")
	public ModelAndView deleteNotice(
			@RequestParam(value = "noticeId") String noticeId)
					throws SQLException {
		int nid = Integer.parseInt(noticeId);
		adminService.deleteNotice(nid);
		return new ModelAndView("redirect:/getNoticeListByPage.action?pageNo=1");
	}

	@RequestMapping(value = "/getOneNotice.action")
	public ModelAndView getOneNotice(
			@RequestParam(value = "noticeId") String noticeId)
					throws SQLException {
		int nid = Integer.parseInt(noticeId);
		NoticeVO nvo = adminService.getOneNotice(nid);
		return new ModelAndView("admin/notice_content", "nvo", nvo);
	}

	@RequestMapping(value = "/getNoticeListByPage.action")
	public ModelAndView getNoticeListByPage(
			@RequestParam(value = "pageNo") String pageNo) throws SQLException {
		NoticeListVO noticeList = adminService.getNoticeListByPage(pageNo);
		return new ModelAndView("admin/notice", "noticeList", noticeList);
	}

	// 타입 가져오기
	/*
	 * @RequestMapping(value="/getMessageType.action") public ModelAndView
	 * getMessageType() throws SQLException{
	 * 
	 * ArrayList<MessageTypeVO> mtList = adminService.getAllMessageType();
	 * System.out.println(mtList); return new
	 * ModelAndView("user/user_write_message","mtList",mtList); }
	 */


	// fileDawnload
	public ModelAndView fileDownload(@RequestParam(value = "") String companyCi)
			throws Exception {
		
		HashMap map = new HashMap();
		map.put("path", savePath); // map에 path를 저장
		return new ModelAndView("downloadView", map); // 빈 설정문서 어떻게 작성할까?
	}

	@RequestMapping(value = "/getAllCompany.action")
	public ModelAndView getAllCompany(@RequestParam(value="flag") int flag) throws SQLException {
		ArrayList<CompanyVO> clist = adminService.getAllCompany();
		
		if( flag==1){
			return new ModelAndView("admin/admin_company_search", "clist", clist);
		}else if( flag==3){
			return new ModelAndView("admin/admin_mentor_search", "clist", clist);
		}else if( flag==4){
			return new ModelAndView("mentor/mentor_search", "clist", clist);
		}
			
		return new ModelAndView("admin/admin_mentor_register", "clist", clist);
		
	}

	@RequestMapping(value = "/addMentor.action")
	public ModelAndView addMentor(
			@RequestParam(value = "companyName") String companyName,
			@RequestParam(value = "userId") String userId) throws SQLException {
		int flag = 0;
		CompanyVO company = adminService.getOneCompanyByName(companyName);
		if(company == null)
			flag = 1;
		else{
			boolean f = adminService.isExist(userId);
			if(f)
				flag =2;
			else{
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("companyId", company.getCompanyId());
				map.put("userId", userId);
				int i = adminService.isExistMentor(map);
				if(i > 0)
					flag = 3;
				else
					adminService.addMentor(new MentorVO(0, company, userId));
			}
		}
		return new ModelAndView("JsonView","flag",flag);
	}
	
	@RequestMapping(value = "/getAllUser.action")
	public ModelAndView getAllUser(HttpSession session) throws SQLException {
		
		AdminVO adminVo = (AdminVO) session.getAttribute("adminVo");
		ArrayList<UserVO> ulist = adminService.getAllUser(adminVo.getAdminId());
		return new ModelAndView("admin/admin_user_delete","ulist",ulist);
	}
	
	@RequestMapping(value = "/deleteUserByAdmin.action")
	public ModelAndView deleteUserByAdmin(
			@RequestParam(value="userId") String userId,
			HttpSession session) throws SQLException {
		
		adminService.deleteUser(userId);
		
		return new ModelAndView("redirect:/getAllUser.action");
	}
	
	@RequestMapping(value = "/getOneUserByUserId.action")
	public ModelAndView getOneUserByUserId(
			@RequestParam(value="userId") String userId,HttpSession session) throws SQLException {
		AdminVO adminVo = (AdminVO)session.getAttribute("adminVo");
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("userId", userId);
		map.put("adminId", adminVo.getAdminId());
		ArrayList<UserVO> ulist = adminService.getOneUserByUserId(map);
	
		return new ModelAndView("admin/admin_user_delete","ulist",ulist);
	}

	@RequestMapping(value = "/getAllMentorByCompanyName.action")
	public ModelAndView getAllMentorByCompanyName(
			@RequestParam(value="companyName") String companyName) throws SQLException {

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("company", "company_name");
		map.put("companyValue", companyName);
		ArrayList<MentorVO> mlist = adminService.getAllMentor(map);
		
		return new ModelAndView("admin/admin_mentor_search","mlist",mlist);
	}
	
	@RequestMapping(value = "/updateMentorPoint.action")
	public ModelAndView updateMentorPoint(
			@RequestParam(value="mentorUserId") String mentorUserId) throws SQLException {

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("point",20 );
		map.put("userId", mentorUserId);
		adminService.updatePointMinus(map);
		
		return new ModelAndView("JsonView");
	}
	
	@RequestMapping(value = "/deleteMentor.action")
	public ModelAndView deleteMentor(
			@RequestParam(value="mentorId") int mentorId,
			@RequestParam(value="companyName") String companyName) throws SQLException {

		adminService.deleteMentor(mentorId);
		
		return new ModelAndView("redirect:/getAllMentorByCompanyName.action?companyName="+companyName);
	}
	
	//fileDawnload
	@RequestMapping(value = "/fileDownload.action")
	public ModelAndView fileDownload2(@RequestParam(value="fileName")String fileName) throws IOException{
			
			HashMap map = new HashMap();
			map.put("path", savePath); //map에 path를 저장
			return new ModelAndView("downloadView", map); //빈 설정문서 어떻게 작성할까?
		}
}
